import { cloneDeep, isObject } from "lodash";

// 基础系统标题配置
const BASE_SYSTEM_LOGO_TITLE_CONFIG = {
  // 布局
  layoutType: 1,
  // 左上角样式
  width: 200,
  fontSize: 12,
  lineHeight: 20,
  color: "#fff",
  letterSpacing: 0,
  paddingLeft: 0,
  paddingTop: 0,
  paddingRight: 0,
  paddingBottom: 0,
  textAlignLast: 1,
  textAlignCenter: 1,
  fontWeightBold: 1,
};

const getDispCssObj = (val) => {
  const flag = isObject(val);
  let tempObj = {};
  if (flag) {
    tempObj = val;
  } else {
    try {
      tempObj = JSON.parse(val);
    } catch (e) {
      tempObj = cloneDeep(BASE_SYSTEM_LOGO_TITLE_CONFIG);
    }
  }
  // 因为后面还会继续添加属性，下面写法是为了兼容旧数据
  Object.keys(BASE_SYSTEM_LOGO_TITLE_CONFIG).map((item) => {
    if (tempObj[item] === undefined) {
      tempObj[item] = BASE_SYSTEM_LOGO_TITLE_CONFIG[item];
    }
  });
  return tempObj;
};

const getFormatedInfo = (val) => {
  const { dispCss, ...rest } = val;
  return { ...rest, dispCss: getDispCssObj(dispCss) };
};

export default {
  namespaced: true,
  state: {
    // 系统配置信息
    info: {},
  },
  actions: {
    /**
     * 设置系统配置文件
     */
    async set({ state, dispatch }, info) {
      const { dispCss, loginBackImg, ...rest } = info;
      // store 赋值
      state.info = getFormatedInfo({
        ...rest,
        dispCss: dispCss || "",
        loginBackImg: loginBackImg || "",
      });
      // 持久化
      await dispatch(
        "d2admin/db/set",
        {
          dbName: "sys",
          path: "sysConfig.info",
          value: state.info,
          user: true,
        },
        { root: true }
      );
    },
    /**
     * 从数据库取系统配置信息
     */
    async load({ state, dispatch }) {
      // store 赋值
      state.info = await dispatch(
        "d2admin/db/get",
        {
          dbName: "sys",
          path: "sysConfig.info",
          defaultValue: {},
          user: true,
        },
        { root: true }
      );
    },
  },
};
